package com.cheifsteam.springframework.beans;

import cn.hutool.core.util.StrUtil;
import com.cheifsteam.springframework.beans.factory.DisposableBean;
import com.cheifsteam.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @author 屈燃希
 * @date 2025/2/15 17:12
 * @content
 */
public class DisposableBeanAdapter implements DisposableBean {


    private final Object bean;


    private final String destroyMethodName;


    private final String beanName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {

        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }


    @Override
    public void destroy() throws Exception {
        // 1. 实现接口 DisposableBean
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }
        // 2. 注解配置 destroy-method {判断是为了避免二次执行销毁}
        if(StrUtil.isNotEmpty(destroyMethodName) &&!(bean instanceof DisposableBean) && "destroy".equals(destroyMethodName)){
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            destroyMethod.invoke(bean);
        }
    }
}
